package com.example.newjiesai.jiesai;

import com.alibaba.fastjson.JSONObject;
import com.example.newjiesai.entity.Location;
import com.example.newjiesai.entity.Point;
import com.example.newjiesai.entity.Realtime;
import com.example.newjiesai.entity.Term;
import com.example.newjiesai.service.Impl.TermServiceImpl;
import com.example.newjiesai.service.LocationService;
import com.example.newjiesai.service.PointService;
import com.example.newjiesai.service.RealtimeService;
import com.example.newjiesai.service.TermService;
import com.example.newjiesai.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class JiesaiDecoder {
    @Autowired
    private TermService termService;
    @Autowired
    private LocationService locationService;
    @Autowired
    private RealtimeService realtimeService;
    @Autowired
    private PointService pointService;
    private int x;

    private byte[] response;
    private String Imei;
    static private  JiesaiDecoder jiasaiDecoder;
    @PostConstruct
    public void init(){
        jiasaiDecoder = this;
    }
    JiesaiMessage message = new JiesaiMessage();

    public String getImei() {
        return Imei;
    }

    public byte[] getResponse() {
        return response;
    }

    public void decode(String data) throws ParseException {
        data = data.substring(0, data.length()-2);          //去掉\r\n
        String[] data_arr = data.split(",");
//        ,801,xCHjegwm/dLC8jLs6fVQwQ==,V1.06,0,uDm7gVdXdlpawaRd5N7sHw==,295,2020-12-19 15:48:0,0,0,0000.0000,00000.0000,00.0,1cc,0,73c1,d283,8f,2,2020-12-19 15:48:0,1,0,1,0,0,-1,15#0#1#240,6,1cc#0#73c1#d285#89|1cc#0#73c1#7cd1#88|1cc#0#73c1#7cbd#85|1cc#0#73c1#fcda#84|1cc#0#73c1#4d5c#82|1cc#0#73c1#1f88#81,24:69:68:d4:ce:f4#34:96:72:81:6a:48#50:50:ce:16:e:4c,-91#-62#-90
        for(int i=0;i<data_arr.length;i++) {            //没电时充电可能会出现801前面有逗号
            if(data_arr[i].equals("801")) {
                x=i;
                break;
            }
        }
        //x = 0;
        message.setType(data_arr[0+x]);                   //将接受的数据存到message
        message.setImei_aes(data_arr[1+x]);
        message.setVersion(data_arr[2+x]);
        message.setPlant(data_arr[3+x]);
        message.setCommand_aes(data_arr[4+x]);
        message.setMes_len(data_arr[5+x]);
        String[] tmp = new String[data_arr.length-6-x];           //把长度选出来了
        System.arraycopy(data_arr, 6+x, tmp, 0, data_arr.length-6-x);
        message.setContent(tmp);

        try {
            message.setCommand(AesUtil.Decrypt(message.getCommand_aes()));      // imei_aes与command_aes解密
            message.setImei(AesUtil.Decrypt(message.getImei_aes()));
            Imei = message.getImei();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("命令： "+message.getCommand());

        if(message.getCommand().equals("u_sk_register")){                       //注册
            System.out.println("-------收到注册消息！-----");
            String[] resp = register();
            response = toData(resp);
            //System.out.println(response);
        }else if(message.getCommand().equals("u_sk_login"))
        {
            register();
            String[] con={"1","222.240.80.68","8001"};         //实际数据就三个字段
            response=toData(con);
        }
        else if(message.getCommand().equals("u_sk_syntim"))
        {
            String[] con={"0",DateUtils.getTime()};
            response=toData(con);
        }else if(message.getCommand().equals("u_sk_pos")){
            System.out.println("-------收到位置消息！-----");
            String[] reps = saveLocation(message.getContent(), 1);
            response = toData(reps);

        }else if(message.getCommand().equals("u_sk_heartbeat"))             //存心跳包
        {
            Term term=jiasaiDecoder.termService.getTerminfoByImei(Imei);
            term.sethrt_pack(data);
            term.sethrt_time(DateUtils.getTime());
            jiasaiDecoder.termService.update(term);
//            String inter="6#01#"+term.getupload_intervel();
 //           String inter="6#01#1";
            String[] con={"1","0"};
            response=toData(con);
        }
        else if(message.getCommand().equals("u_sk_workflow"))
        {
            String[] con={"1"};
            response=toData(con);
        }
        else if(message.getCommand().equals("u_sk_disconnect"))
        {
            String[] con=saveLocation(message.getContent(),2);
            response=toData(con);
        }
        else if(message.getCommand().equals("u_sk_batlow"))
        {
            String[] con=saveLocation(message.getContent(),3);
            response=toData(con);
        }
        else if(message.getCommand().equals("u_sk_shutdown"))
        {
            String[] con=saveLocation(message.getContent(),4);
            response=toData(con);
        }
        else if(message.getCommand().equals("u_sk_power_on"))
        {
            String[] con=saveLocation(message.getContent(),5);
            response=toData(con);
        }else if(message.getCommand().equals("u_sk_configure"))
        {  Term term=jiasaiDecoder.termService.getTerminfoByImei(Imei);
            String inter="6#01#"+term.getupload_intervel();

            String[] con={"1","2",inter,"08#1#222.240.80.68:8001"};

            response=toData(con);
        }else if(message.getCommand().equals("u_sk_offline"))
        {
            response=toData2();
        }


    }

    public String[] register(){
        System.out.println("imei:" + Imei);
        if(null==jiasaiDecoder.termService.getTerminfoByImei(Imei)){        //不加类名报空指针异常
            Term term = new Term();
            term.setterm_typee(1);
            term.setterm_imei(message.getImei());
            term.setterm_provider(3);
            term.setterm_version(message.getVersion());
            term.setregister_time(DateUtils.getTime());
            System.out.println(term);
            jiasaiDecoder.termService.add(term);                          //-------没加jiesaidecoder
        }

        return new String[]{"1","C544E974FCA2A884","success",DateUtils.dateTimeNow("yyMMddHHmmss")};
    }

    public String[] saveLocation(String[] content, int type) throws ParseException {

        Location location = new Location();                                      //位置表每次都新添加一个位置
        Term term = jiasaiDecoder.termService.getTerminfoByImei(Imei);           //设备表更新设备的最新位置
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(term.getlocation_time().length()!=0 && type!=1) {
            Date termtime = sdf.parse(term.getlocation_time());          //上次定位时间
            Date lotime = sdf.parse(content[12]);           //插电时时间为空

            if ((lotime.getTime() - termtime.getTime()) <= 0) {         //判断传输的时间不正确的情况
                return new String[]{"01", "0"};
            }
        }

        location.setterm_imei(Imei);                    //IMEI
        String location_time = content[12];
       // System.out.println("time: "+location_time);              //2020-12-15 14:48:0                   //Location表location_time没存进去？？？？？
        Date parse = sdf.parse(location_time);          //标准化
        location_time = sdf.format(parse);
        System.out.println("time: "+location_time);

        location.setlocation_time(location_time);       //location_time
        term.setlocation_time(location_time);
        int batvalue = Integer.parseInt(content[13]);   //batvalue
        location.setbatvalue(batvalue);
        term.setbatvalue(batvalue);
        if(type==1)                                 //u_sk_pos
        {
            term.setchainstate(1);                  //腕表连接
        }
        else if(type==2)                           //u_sk_disconnect
        {
            term.setchainstate(0);                   //腕表拆卸
        }

        String gps_lat = null;
        String gps_lng = null;
        String gps_pot = null;
        String wifi_lat = null;
        String wifi_lng = null;
        String wifi_pot = null;
        String lbs_lat = null;
        String lbs_lng = null;
        String lbs_pot = null;



        //---------------------gps----------
        gps_lat = content[3];
        gps_lng = content[4];
        gps_pot = BaiduAPI.getLocName(gps_lat, gps_lng);
        System.out.println("gps_lat: " + gps_lat);
        System.out.println("gps_lng: " + gps_lng);
        System.out.println("gps_pot: " + gps_pot);
        System.out.println("-----------------------");



        //-------------------wifi---------------
        if(content[11].equals("2")){                        //定位方式为2时，才有wifi mac地址
            String[] macs = content[22].split("#");         //mac
            String[] signal = content[23].split("#");       //信号强度
            String macs_final = "";
            for(int i=0; i<macs.length; i++){
                if(i != macs.length-1) macs_final = macs_final + macs[i] + "," + signal[i] + "," + "TPLink" + "|";
                else macs_final = macs_final + macs[i] + "," + signal[i] + "," + "TPLink";
            }
            System.out.println("macs: " + macs_final);

            JSONObject jsonObject = GaodeAPI.getLocByWifi(Imei, macs_final);
            if(!jsonObject.getJSONObject("result").getString("type").equals("0")){      //不为0，收到位置信息
                String[] gps = jsonObject.getJSONObject("result").getString("location").split(",");
                wifi_lat = gps[1];
                wifi_lng = gps[0];
                wifi_pot = jsonObject.getJSONObject("result").getString("desc");
            }
            System.out.println("wifi_lat: " + wifi_lat);
            System.out.println("wifi_lng: " + wifi_lng);
            System.out.println("wifi_pot: " + wifi_pot);
        }


        //------------------------bts--------------
        String bts=Integer.parseInt(content[6], 16)+","+Integer.parseInt(content[7], 16)+","                         //这里转16进制根据具体设备测试来的
                +Integer.parseInt(content[8], 16)+","+Integer.parseInt(content[9], 16)+","+Integer.parseInt(content[10], 16);

        String nearbts = content[21];                                  //处理基站信息
        nearbts = nearbts.replace("\r", "");
        nearbts = nearbts.replace("|", "#");
        String nearbts_final = "";
        String[] nearbts_arr = nearbts.split("#");
        for(int i=0; i<nearbts_arr.length; i++){
            if((i+1)%5 != 0) {
                nearbts_final += Integer.parseInt(nearbts_arr[i], 16) + ",";
            }else if((i+1)%5==0 && i!=nearbts_arr.length-1){
                nearbts_final += Integer.parseInt(nearbts_arr[i], 16) + "|";
            }else{
                //System.out.println("nearbts_arr: "+nearbts_arr[i]);
                //System.out.println("len: "+nearbts_arr[i].length());
                nearbts_final += Integer.parseInt(nearbts_arr[i], 16);

//                char[] lastn = new char[2];
//                lastn[0] = nearbts_arr[i].charAt(0);
//                lastn[1] = nearbts_arr[i].charAt(1);
//                nearbts_final += Integer.parseInt(new String(lastn), 16);
            }
        }

        System.out.println("-------------------------------");
        System.out.println("bts: "+bts);
        System.out.println("nearbts: "+nearbts_final);

        JSONObject jsonObject1 = GaodeAPI.getLocByLBS(Imei, bts, nearbts_final);
        if(!jsonObject1.getJSONObject("result").getString("type").equals("0")) {
            String[] lbagps = jsonObject1.getJSONObject("result").getString("location").split(",");
            lbs_lat = lbagps[1];
            lbs_lng = lbagps[0];
            lbs_pot = jsonObject1.getJSONObject("result").getString("desc");
        }
        System.out.println("lbs_lat: " + lbs_lat);
        System.out.println("lbs_lng: " + lbs_lng);
        System.out.println("lbs_pot: " + lbs_pot);



//        Point point = new Point();                                                        //在实时数据库中创建Point点
//        point.setRT(4);
//        point.setGN("W3.LOCATION." + Imei + "_LNG");
//        jiasaiDecoder.pointService.insert(point);                                         //插入经度Point点
//        point.setGN("W3.LOCATION." + Imei + "_LAT");                                      //插入纬度Point点
//        jiasaiDecoder.pointService.insert(point);
//
//        Realtime realtime = new Realtime();
        if(!gps_lat.equals("0000.0000")&&!gps_pot.equals("")){
            location.setlocation_lat(gps_lat);
            location.setlocation_lng(gps_lng);
            location.setlocation_name(gps_pot);
            location.setLocation_type(1);
            jiasaiDecoder.locationService.add(location);                    //在mysql中插入经纬度
            term.setlocation_lat(gps_lat);
            term.setlocation_lng(gps_lng);
            term.setlocation_name(gps_pot);
            term.setlocation_type(1);

//            realtime.setGN("W3.LOCATION." + Imei + "_LNG");
//            realtime.setAV(Double.valueOf(gps_lng));                      //------当s_lng为null的时候有空指针异常
//            jiasaiDecoder.realtimeService.insert(realtime);
//            realtime.setGN("W3.LOCATION." + Imei + "_LAT");
//            realtime.setAV(Double.valueOf(gps_lat));
//            jiasaiDecoder.realtimeService.insert(realtime);                 //在实时数据库中插入经纬度

        }else if(wifi_lat!=null && wifi_pot.contains("湖南")){
            location.setlocation_lat(wifi_lat);
            location.setlocation_lng(wifi_lng);
            location.setlocation_name(wifi_pot);
            location.setLocation_type(2);
            jiasaiDecoder.locationService.add(location);
            term.setlocation_lat(wifi_lat);
            term.setlocation_lng(wifi_lng);
            term.setlocation_name(wifi_pot);
            term.setlocation_type(2);

//            realtime.setGN("W3.LOCATION." + Imei + "_LNG");
//            realtime.setAV(Double.valueOf(wifi_lng));                      //------当s_lng为null的时候有空指针异常
//            jiasaiDecoder.realtimeService.insert(realtime);
//            realtime.setGN("W3.LOCATION." + Imei + "_LAT");
//            realtime.setAV(Double.valueOf(wifi_lat));
//            jiasaiDecoder.realtimeService.insert(realtime);                 //在实时数据库中插入经纬度
        }else if(lbs_lat!=null){
            location.setlocation_lat(lbs_lat);
            location.setlocation_lng(lbs_lng);
            location.setlocation_name(lbs_pot);
            location.setLocation_type(4);
            jiasaiDecoder.locationService.add(location);
            term.setlocation_lat(lbs_lat);
            term.setlocation_lng(lbs_lng);
            term.setlocation_name(lbs_pot);
            term.setlocation_type(4);

//            realtime.setGN("W3.LOCATION." + Imei + "_LNG");
//            realtime.setAV(Double.valueOf(lbs_lng));                      //------当s_lng为null的时候有空指针异常
//            jiasaiDecoder.realtimeService.insert(realtime);
//            realtime.setGN("W3.LOCATION." + Imei + "_LAT");
//            realtime.setAV(Double.valueOf(lbs_lat));
//            jiasaiDecoder.realtimeService.insert(realtime);                 //在实时数据库中插入经纬度
        }

        if(term.getif_upload()==0) {                                        //设置上传
            String[] con = {"01","1","6#01#"+term.getupload_intervel()};          //状态#操作#具体数据
            term.setif_upload(1);
            jiasaiDecoder.termService.update(term);
            return con;
        }
        else{
            String[] con = {"01","0"};
            jiasaiDecoder.termService.update(term);
            UploadUtil.uploadToConverter(term);                             //发给转发器
            return con;
        }

    }
    /*
            if_chain
            chainstate      这两个是默认值
            if_upload
            upload_intervel     这两个也是默认值，没有指令设置，只能取值
     */




    public byte[] toData(String[] resp){                //将内容与消息头合并
        String mes_1 = message.getType() + "," + message.getImei_aes() + "," + message.getVersion() + ","       //消息头是一致的
                + message.getPlant() + "," +message.getCommand_aes() + ",";
        int len = 0;
        String mes_2 = "";
        for(int i=0; i<resp.length; i++){
            mes_2 = mes_2 + "," + resp[i];
            len = len + resp[i].length();
        }
        len += 3;                          //设备对这个长度貌似没有处理,写成3多个设备没错误，写0，1，2单个设备也没问题（设备发过来的有些算了逗号，有些没有算）

        String mes = mes_1 + len + mes_2 + "\r\n";
        return mes.getBytes();
    }

    private byte[] toData2()
    {
        String input =message.getType()+","+message.getImei_aes()+","+message.getVersion()
                +","+message.getPlant()+","+message.getCommand_aes()+","+"1";
        input += "\r\n";

        return input.getBytes();

    }


}
